﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Configuration;
using SharpShare.Configuration;
using System.Diagnostics;

namespace SharpShare.Service {
    public static class Program {
        private static ServiceController _serviceController;
        public static System.Configuration.Configuration _configuration;

        static ServiceController GetServiceController() {
            return ServiceController.GetServices().Where(s => s.ServiceName == "SharpShare").FirstOrDefault();
        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        public static void Main(string[] args) {
            if (args != null && args.Length > 0) {
                while (args.Length % 2 != 0) {
                    args = args.Concat(new string[] { "" }).ToArray();
                }

                for (int x = 0; x < args.Length; x += 2) {
                    string[] a = new string[2];
                    Array.Copy(args, x, a, 0, 2);
                    if (!HandleCommandLine(a)) {
                        return;
                    }
                }
            }

            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
			{ 
				new Service() {
                     Configuration = _configuration
                }
			};
            ServiceBase.Run(ServicesToRun);
        }

        static bool HandleCommandLine(string[] args) {

            bool pushKeyToExit = false;

            switch (args[0]) {
                case "configuration": {
                        string path = args[1];
                        ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = path };

                        _configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

                        return true;
                    }
                case "manage": {
                        string mscPath = args[1];

                        ProcessStartInfo startInfo = new ProcessStartInfo("mmc.exe", "\"" + mscPath + "\"") {
                            UseShellExecute = false
                        };
                        startInfo.EnvironmentVariables.Add("COMPLUS_Version", "v4.0.30319");

                        Process.Start(startInfo);

                        break;
                    }
                case "edit-configuration": {
                        string configPath = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None).FilePath;

                        System.Diagnostics.Process.Start("notepad.exe", configPath);
                        break;
                    }
                case "console": {
                        ConsoleProgram.ConsoleMain(args);
                        break;
                    }
                case "toggle-service": {
                        ServiceController c = GetServiceController();

                        if (c == null) {
                            Console.WriteLine("Service not installed.");
                            pushKeyToExit = true;
                            break;
                        }

                        if (c.Status == ServiceControllerStatus.Running) {
                            Console.WriteLine("Stopping...");
                            c.Stop();
                        } else if (c.Status == ServiceControllerStatus.Stopped) {
                            Console.WriteLine("Starting...");
                            c.Start();
                        } else {
                            Console.WriteLine("Unknown status: {0}", c.Status);
                            pushKeyToExit = true;
                        }

                        break;
                    }
                default: {
                        Console.WriteLine("Unrecognized command line option: {0}", args[0]);
                        pushKeyToExit = true;
                        break;
                    }
            }

            if (pushKeyToExit) {
                Console.WriteLine("Push any key to exit...");
                Console.ReadKey(true);
            }

            return false;
        }
    }
}
